package com.logic.modular.game.player.bag.service;



import com.logic.comment.util.RedisUtils;
import com.logic.config.netty.web.service.MessageService;
import com.logic.modular.game.GameConstant;
import com.comment.pojo.domain.bag.Bag;
import com.logic.modular.game.player.bag.mapper.BagMapper;
import com.comment.pojo.domain.logic.core.CoreAccountConfig;
import com.logic.modular.gameCore.config.service.impl.CoreAccountConfigServiceImpl;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 背包物品(Bag)表服务实现类
 * 玩家操作背包需获操作权
 *
 * @author cxy
 * @since 2024-11-13 15:04:13
 */
@Slf4j
@Service

public class BagServiceImpl extends ServiceImpl<BagMapper, Bag> {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private BagItemServiceImpl bagItemService;

    public void updateById(Long playerId, Bag bag) {
        if (bag.updateById()) {
            saveCache(bag);
            MessageService.sendMessageToUser(playerId, MessageService.updateJsonObject("bag", bag));
        } else {
            String info = String.format("玩家:%d,背包数据更新失败", playerId);
            log.info(info);
        }
    }

    private void saveCache(Bag byId) {
        String key = String.format(GameConstant.PLAYER_BAG_KEY, byId.getUid());
        redisUtils.set(key, byId, 30L, TimeUnit.DAYS);
    }

    /**
     * 获取背包
     *
     * @param playerId 玩家id
     * @return 背包
     */
    public Bag obtainBag(Long playerId) {
        Bag byId = getById(playerId);
        if (byId == null) {
            byId = new Bag();
            byId.setUid(playerId);
            boolean insert = byId.insert();
            if (insert) {
                saveCache(byId);
                byId = getById(playerId);
            }
        }
        return byId;
    }

    // 注册init
    public void registerInit(Long playerId) {
        CoreAccountConfig coreAccountConfig = CoreAccountConfigServiceImpl.getCache(1L);
        Map<Long, Integer> propInfo = coreAccountConfig.getProp();
        propInfo.forEach((corePropId, num) -> bagItemService.obtainBagItem(playerId, corePropId, BigDecimal.valueOf(num)));
    }
}